<?php
/**
 * GioCMS
 * 
 * LICENSE
 *
 * This source file is subject to the GNU GENERAL PUBLIC LICENSE Version 2 
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-2.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@ninhgio.com so we can send you a copy immediately.
 * 
 * @copyright	Copyright (c) 2010-2011 GioCMS (http://cms.ninhgio.com)
 * @license		http://www.gnu.org/licenses/gpl-2.0.txt GNU GENERAL PUBLIC LICENSE Version 2
 * @author		NinhGio - ninhgio@gmail.com
 * @since		1.0
 */

class Modules_News_Services_Article
{
	const EOL = "\n";
	
	public static function validate($data)
	{
		$validator = new Gio_Core_Validator();
		foreach ($data as $index => $value) {
			if (gettype($value) == 'string') {
				$data[$index] = trim($value);
			}
		} 
		
		$data['messages']['title'] = $validator->setString($data['title'])
												->validate(array('notNull')
																, array(
																	'notNull' => 'article_title_notnull',
																)
														);
		
		$data['messages']['slug'] = $validator->setString($data['slug'])
												->validate(array('notNull', 'isSlug')
																, array(
																	'notNull' => 'article_slug_notnull',
																	'isSlug' => 'article_slug_invalid',
																)
														);
		
		$descriptionTemp = Gio_Core_String::stripTags($data['description'], null);
		$data['messages']['description'] = $validator->setString($descriptionTemp)
												->validate(array('notNull')
																, array(
																	'notNull' => 'article_description_notnull',
																)
														);
														
		$contentTemp = Gio_Core_String::stripTags($data['content'], null);
		$data['messages']['content'] = $validator->setString($contentTemp)
												->validate(array('notNull')
																, array(
																	'notNull' => 'article_content_notnull',
																)
														);
														
		$data['messages']['category_id'] = $validator->setString($data['category_id'])
												->validate(array('isNumeric')
																, array(
																	'isNumeric' => 'article_category_id_invalid',
																)
														);
		
		$error = false;
		foreach ($data['messages'] as $index => $message) {
			if ($message) {
				$data['messages_error'] = true;
				return $data;
			}
		}										
		$data['messages_error'] = false;
		return $data; 
	}
	
	public static function add($article, $categories = array(), $sourceItem = null)
	{
		$conn		= Gio_Db_Connection::getConnection();
		$dao = new Modules_News_Models_Mysql_Article();
		$dao->setConnection($conn);
		$id = $dao->add($article);
		
		if ($id) {
			/**
			 * Add translation relation
			 */
			$json 		 = new Services_JSON();
			$source 	 = (array)$json->decode($sourceItem);
			$translation = array(
								'item_id' 	      => $id,
								'item_class'      => get_parent_class($dao),
								'source_item_id'  => (!isset($source['article_id']) || $source['article_id'] == '') ? $id : $source['article_id'],
								'language'        => $article['language'],
								'source_language' => (!isset($source['language']) || '' == $source['language']) ? null : $source['language'],
						);
			Modules_Core_Services_Translation::add($translation);
			
			/**
			 * Add to categories
			 */
			if (is_array($categories) && !empty($categories)) {
				if (!in_array($article['category_id'], $categories)) {
					$categories[] = $article['category_id'];
				}
			} else {
				$categories[] = $article['category_id'];
			}
			
			$dao->addToCategories($id, $categories);
			
			/**
			 * Add to hot collection
			 */
//			$dao->removeFromHot($id);
//			if ($article->is_hot) {
//				$dao->addHotArticle($id);
//			}
			
			/**
			 * Execute hooks
			 */
			Gio_Core_Hook_Registry::getInstance()->executeAction('News_Article_Add_Success', $id);
		}
		return $id;
	}
	
	/**
	 * Increase the number of views
	 * 
	 * @param Array
	 */
	public static function increaseViews($article)
	{
		$cookieName = 'Modules_News_Services_Article_increaseViews';
		$viewed     = false;
		
		if (!isset($_COOKIE[$cookieName])) {
			setcookie($cookieName, $article['article_id'], time() + 3600);
		} else {
			if (strpos($_COOKIE[$cookieName], $article['article_id']) === false) {
				$cookie = $_COOKIE[$cookieName] . ',' . $article['article_id'];
				setcookie($cookieName, $cookie);
			} else {
				$viewed = true;
			}
		}
		if (!$viewed) {
			$conn		= Gio_Db_Connection::getConnection();
			$dao = new Modules_News_Models_Mysql_Article();
			$dao->setConnection($conn);
			return $dao->increaseViews($article['article_id']);
		}
	}
	
	public static function update($article, $categories = array())
	{
		$conn		= Gio_Db_Connection::getConnection();
		$dao = new Modules_News_Models_Mysql_Article();
		$dao->setConnection($conn);
		$dao->update($article);
		
		/**
		 * Update translation relation
		 */
		$json 		 = new Services_JSON();
		$source 	 = self::getSource($article);
		$translation = array(
								'item_id' 	      => $article['article_id'],
								'item_class'      => get_parent_class($dao),
								'source_item_id'  => (!isset($source['article_id']) || $source['article_id'] == '') ? $article['article_id'] : $source['article_id'],
								'language'        => $article['language'],
								'source_language' => (!isset($source['language']) || '' == $source['language']) ? null : $source['language'],
						);
		if ($source != null) {
			Modules_Core_Services_Translation::update($translation);
		} else {
			Modules_Core_Services_Translation::add($translation);
		}
		
		/**
		 * Add to categories
		 */
		if (is_array($categories) && !empty($categories)) {
			if (!in_array($article['category_id'], $categories)) {
				$categories[] = $article['category_id'];
			}
		} else {
			$categories[] = $article['category_id'];
		}
		
		$dao->addToCategories($article['article_id'], $categories);
		
		/**
		 * Execute hooks
		 */
		Gio_Core_Hook_Registry::getInstance()->executeAction('News_Article_Edit_Success', $article['article_id']);
	}
	
	public static function getCategoryIds($article)
	{
		$conn		= Gio_Db_Connection::getConnection();
		$dao = new Modules_News_Models_Mysql_Article();
		$dao->setConnection($conn);
		return $dao->getCategoryIds($article['article_id']);
	}
	
	public static function getOlderArticles($article, $limit, $categoryId = null)
	{
		$conn		= Gio_Db_Connection::getConnection();
		$dao = new Modules_News_Models_Mysql_Article();
		$dao->setConnection($conn);
		return $dao->getOlderArticles($article, $limit, $categoryId);
	}
	
	public static function getNewerArticles($article, $limit, $categoryId = null)
	{
		$conn		= Gio_Db_Connection::getConnection();
		$dao = new Modules_News_Models_Mysql_Article();
		$dao->setConnection($conn);
		return $dao->getNewerArticles($article, $limit, $categoryId);
	}
	
	public static function activate($article)
	{
		$conn		= Gio_Db_Connection::getConnection();
		$dao = new Modules_News_Models_Mysql_Article();
		$dao->setConnection($conn);
		return $dao->update($article);
	}
	
	public static function countNewsOfDay($date)
	{
		$conn		= Gio_Db_Connection::getConnection();
		$articleDao = new Modules_News_Models_Mysql_Article();
		$articleDao->setConnection($conn);
		return $articleDao->countNewsOfDay($date);
	}
	
	public static function count($condition)
	{
		$conn	= Gio_Db_Connection::getConnection();
		$dao 	= new Modules_News_Models_Mysql_Article();
		$dao->setConnection($conn);
		return $dao->count($condition);
	}
	
	public static function find($start, $limit, $condition = array())
	{
		$conn		= Gio_Db_Connection::getConnection();
		$articleDao = new Modules_News_Models_Mysql_Article();
		$articleDao->setConnection($conn);
		return $articleDao->find($start, $limit, $condition);
	}
	
	public static function getById($id, $active = false)
	{
		$conn		= Gio_Db_Connection::getConnection();
		$articleDao = new Modules_News_Models_Mysql_Article();
		$articleDao->setConnection($conn);
		return $articleDao->getById($id, $active);
	}
	
	public static function getHotArticle($limit, $categoryId)
	{
		$conn		= Gio_Db_Connection::getConnection();
		$articleDao = new Modules_News_Models_Mysql_Article();
		$articleDao->setConnection($conn);
		return $articleDao->getHotArticle($limit, $categoryId);
	}
	
	public static function getMostViewedArticle($categoryId, $limit)
	{
		$conn		= Gio_Db_Connection::getConnection();
		$articleDao = new Modules_News_Models_Mysql_Article();
		$articleDao->setConnection($conn);
		return $articleDao->getMostViewedArticle($categoryId, $limit);
	}
	
	public static function getLatestArticle($categoryId = null, $limit = 5)
	{
		$conn		= Gio_Db_Connection::getConnection();
		$articleDao = new Modules_News_Models_Mysql_Article();
		$articleDao->setConnection($conn);
		return $articleDao->getLatestArticle($categoryId, $limit);
	}
	
	public static function getPhotoArticles($limit)
	{
		$conn		= Gio_Db_Connection::getConnection();
		$articleDao = new Modules_News_Models_Mysql_Article();
		$articleDao->setConnection($conn);
		return $articleDao->getPhotoArticles($limit);
	}
	
	/**
	 * Display select box listing all articles
	 * which haven't been translated from the default language
	 * 
	 * @param $attributes array
	 * @param string $lang
	 * @return string
	 */
	public static function translatableArticle($attributes = array(), $lang = null)
	{
		$limit 				 = isset($attributes['limit']) ? ($attributes['limit'] + 10) : 10;
		$attributes['limit'] = $limit;
		
		$view = Gio_Core_View::getInstance();
		
		$json = new Services_JSON();
		$defaultLang     = (string)Gio_Core_Config_Xml::getConfig('web')->language;
		$lang = (null == $lang) ? $defaultLang : $lang;
		$elementDisabled = (null == $lang || $lang == $defaultLang) ? ' disabled="disabled"' : '';
		
		$attributes['selected'] = isset($attributes['selected']) ? $attributes['selected'] : null;
		$attributes['disabled']  = isset($attributes['disabled']) ? $attributes['disabled'] : null;
		
		$articles 	 = self::getTranslatable($lang, $limit, $attributes['selected']);
		$output 		 = sprintf("<select name='%s' id='%s' viewHelperClass='%s' viewHelperAttributes='%s'%s>", 
								$attributes['name'], 
								$attributes['id'],
								'Modules_News_Services_Article::translatableArticle',
								$json->encodeUnsafe($attributes), 
								$elementDisabled) . self::EOL
						. '<option value=\'{"id": "", "language": ""}\'>---</option>' . self::EOL;
		
		foreach ($articles as $article) {
			$disabled = (0 == (int)$article['translatable'] 
							&& ((0 == (int)$attributes['disabled'] && $article['article_id'] != (int)$attributes['selected'])
								||
							((int)$attributes['disabled'] == (int)$attributes['selected'])))
						? ' disabled="disabled"' 
						: '';
			$selected = ($elementDisabled == ''
							&& $disabled == ''
							&& (int)$article['article_id'] == (int)$attributes['selected'])
						? ' selected="selected"' 
						: '';
			
			$output  .= sprintf("<option value='%s'%s%s>%s</option>", 
								$json->encodeUnsafe(array('id' => $article['article_id'], 'language' => $defaultLang)), 
								$selected,
								$disabled,
								$article['title']) . self::EOL;
		}
		$output .= '<option value="">' . $view->TRANSLATOR->translator('helper_translatable_article_more', 'news') . '</option>';
		$output .= '</select>' . self::EOL;

		$id = $attributes['id'];
		$url = $view->url('core_locale_viewhelper');
		
		$scripts = <<<END
		<script type="text/javascript">
			$(document).ready(function() {
				$('#$id').change(function() {
					if ($(this).val() != '') {
						return;
					}
			
					/**
					 * Load more articles
					 */
					var self   = this;
					var parent = $(self).parent(); 
					$(parent).addClass('g_a_ajax_loading');
					
					$.ajaxq('Core_View_Helper_LanguageSelector', {
						url: '$url',
						type: 'POST',
						data: {
							id: $(self).attr('id'), 
							name: $(self).attr('name'), 
							language: '$lang',
							viewHelperClass: $(self).attr('viewHelperClass'), 
							viewHelperAttributes: $(self).attr('viewHelperAttributes') 
						},
						success: function(response) {
							$(parent).html(response).removeClass('g_a_ajax_loading');
			
							/**
							 * Disable source items element if user select the default language
							 */
							if ('$lang' == '$defaultLang') {
								$(self).attr('disabled', 'disabled').find('option:selected').removeAttr('selected');
							} else {
								$(self).removeAttr('disabled');
							}
						}
					});
				});
			});
		</script>
END;
		
		return $output . $scripts;
	}
	
	public static function getTranslatable($lang, $count , $selected = null)
	{
		$conn		= Gio_Db_Connection::getConnection();
		$dao = new Modules_News_Models_Mysql_Article();
		$dao->setConnection($conn);
		return $dao->getTranslatable($lang, $count, $selected);
	}
	
	public static function getSource($article)
	{
		$conn		= Gio_Db_Connection::getConnection();
		$dao = new Modules_News_Models_Mysql_Article();
		$dao->setConnection($conn);
		return $dao->getSource($article);
	}
}